'use strict';

import React from 'react'
import PropTypes from 'prop-types'
import { withStyles } from '@material-ui/core/styles'
import {
  TextField,
  Button,
  CircularProgress,
  FormControlLabel,
  Checkbox,
  Snackbar,
} from '@material-ui/core'

import config from '../config'

const electron = window.require('electron')

const styles = theme => ({
  root: {
    position: 'absolute',
    left: 0,
    top: 0,
    bottom: 0,
    display: 'flex',
    flex: 1,
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
    paddingTop: 220,
    paddingLeft: 120,
    paddingRight: 120,
    width: 240,
    overflowX: 'hidden'
  },
  h2: {
    position: 'absolute',
    top: 60,
    right: 40,
    fontFamily: 'FZYaoti',
    textShadow: '2px 2px 2px #D4D4D4',
    color: '#4244BC',
    fontSize: '1.5em',
    fontWeight: 900
  },
  shadow: {
    top: 0,
    position: 'absolute',
    width: 560,
    height: 200
  },
  password: {
    marginTop: 10,
  },
  buttons_container: {
    marginTop: 12,
    width: '100%',
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center'
  },
  button: {
    width: '180px !important',
    borderRadius: 0,
  },
  copyright:{
    position:'absolute',
    right: 40,
    top: 176,
    color: '#999999',
    fontSize: 10,
    cursor: 'pointer'
  },
  check_container: {
    flexDirection: 'row',
    marginLeft: 12,
    width: 256
  },
  checkbox: {
    width: 128,
    marginLeft: 150,
    marginTop: 10,
    color: '#00ABAF',
  }
});

class LoginBox extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      userName: '',
      password: '',
      alert: props.msg,
      record: false,
      loging: false,
    }
  }
  
  componentWillMount () {
    let username = localStorage.getItem('username');
    let pwd = localStorage.getItem('password');
    let record  = localStorage.getItem('record') == 'true';
    this.setState({
      userName: username,
      password: pwd,
      record: record
    })
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.msg) {
      this.setState({
        alert: nextProps.msg,
        loging: false,
      });
    }
  }

  keypressUsernameHandle(evt){
    if(evt.key == 'Enter'){
      this.passwordInput.focus();
    }
  }

  keypressPasswordHandle(evt){
    if(evt.key == 'Enter'){
      this._handleLogin();
    }
  }

  _handleExit() {
    this.props.onExit();
  }

  _handleLogin() {
    this.setState({ loging: true })
    if (this.state.userName.trim().length == 0) {
      return this.setState({ alert: "用户名为空" });
    }
    if (this.state.password.length == 0) {
      return this.setState({ alert: "密码为空" });
    }
    if(this.state.record){
      localStorage.setItem('username', this.state.userName);
      localStorage.setItem('password', this.state.password);
      localStorage.setItem('record', this.state.record);
    }else{
      localStorage.setItem('username', '');
      localStorage.setItem('password', '');
      localStorage.setItem('record', false);
    }
    this
      .props
      .onLogin(this.state.userName.trim(), this.state.password)
  }

  render() {
    const { classes } = this.props;
    return (
      <div>
        <div className={classes.root}>
          <img className={classes.shadow} src='./public/images/shadow.png'/>
          
          <h2 className={classes.h2}>{config.title}</h2>
          <TextField
            autoFocus
            fullWidth
            placeholder='请输入用户名'
            value={this.state.userName}
            onKeyPress={this.keypressUsernameHandle.bind(this)}
            onChange={(event) => {
            this.setState({userName: event.target.value})
          }}/>
          <TextField
            className={classes.password}
            fullWidth
            placeholder='请输入密码'
            inputRef={(input) => { this.passwordInput = input }}
            type='password'
            value={this.state.password}
            onKeyPress={this.keypressPasswordHandle.bind(this)}
            onChange={(event) => {
            this.setState({password: event.target.value})
          }}/>

          <div className={classes.buttons_container}>
            <Button
              className={classes.button}
              variant="raised"
              color="primary"
              size="medium"
              disabled={this.state.loging}
              style={{marginRight: 16}}
              onClick={() => this._handleLogin()}
            >
              {this.state.loging?<CircularProgress size={20} thickness={6} />:<div />}
              登  录
            </Button>
            <Button
              className={classes.button}
              variant="raised"
              color="secondary"
              size="medium"
              onClick={() => this._handleExit()}
            >
              退  出
            </Button>
          </div>

          <div className={classes.check_container}>
            <FormControlLabel
              control={
                <Checkbox
                  checked={this.state.record}
                  value="record"
                  onChange={(e) => this.setState({record: e.target.checked})}
                />
              }
              label="记住密码"
            />
            
          </div>
          <a
            className={classes.copyright} 
            onClick={()=> electron.shell.openExternal('tel:13255801068')}>@xuepx</a>
        </div>
        <Snackbar
          open={this.state.alert.length>0}
          message={this.state.alert}
          autoHideDuration={2000}
          onClose={()=>this.setState({alert:""})}
          />
      </div>
    )
  }
}

LoginBox.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(LoginBox);